package com.xexun.gpstracker.baby.activity;

import java.util.HashMap;
import java.util.Map;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.common.MyConstants;
import com.xexun.gpstracker.my.activity.AlarmActivity;
import com.xexun.gpstracker.my.activity.StepCountingActivity;
import com.xexun.gpstracker.my.activity.TerminalEmojiSet;
import com.xexun.gpstracker.my.activity.WifiActivity;
import com.xexun.gpstracker.pojo.ChatMsg;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.vo.Cmd;
import com.xexun.gpstracker.vo.CmdType;
import com.xexun.gpstracker.vo.ContType;
import com.xexun.gpstracker.vo.Session;

/**
 * Created by Admin on 2015/8/27 0027.
 */
public class ChatTerMianlAddTwoFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = ChatTerMianlAddTwoFragment.class.getSimpleName();

    @ViewInject(R.id.add_overstep_police)
    private LinearLayout addOverstepPolice;
    @ViewInject(R.id.add_low_power)
    private LinearLayout addLowPower;
    @ViewInject(R.id.add_home_wifi)
    private LinearLayout addHomeWifi;
    @ViewInject(R.id.add_remote_shutdown)
    private LinearLayout addRemoteShutdown;
    @ViewInject(R.id.add_alarm)
    private LinearLayout addAlarm;

    @ViewInject(R.id.add_remote_listener)
    private LinearLayout addRemoteListener;

    @ViewInject(R.id.add_set_terminal_emoji)
    private LinearLayout addSetTerminalEmoji;
    @ViewInject(R.id.step_counting)
    private LinearLayout stepCounting;
    @ViewInject(R.id.add_blacklist)
    private LinearLayout blacklist;

    private View view;
    private Context mContext;
    private Intent intentMsg;
    private Map<Integer, Long> countTime = new HashMap<>();


    //创建Fragment对象
    public static ChatTerMianlAddTwoFragment newInstance() {
        ChatTerMianlAddTwoFragment newFragment = new ChatTerMianlAddTwoFragment();
        return newFragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_add_two, container, false);
        x.view().inject(this, view);
        initEvent();
        return view;
    }

    private void initEvent() {
        addHomeWifi.setOnClickListener(this);
        addRemoteShutdown.setOnClickListener(this);
        addOverstepPolice.setOnClickListener(this);
        addLowPower.setOnClickListener(this);
        addAlarm.setOnClickListener(this);
        addRemoteListener.setOnClickListener(this);
        addSetTerminalEmoji.setOnClickListener(this);
        stepCounting.setOnClickListener(this);
        blacklist.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        long curr = System.currentTimeMillis();
        long last = CommUtil.toLong(countTime.get(v.getId()), 0L);
        if (curr - last < Constants.REQUEST_INTERVAL) {
            Toast.makeText(mContext, R.string.foot_menu_prompt, Toast.LENGTH_SHORT).show();
            return;
        }
        countTime.put(v.getId(), curr);
        Session.getInstance().setSetupDevice(ChatActivity.device);
        switch (v.getId()) {
            case R.id.add_set_terminal_emoji:
                //设置终端表情
                startActivity(new Intent(mContext, TerminalEmojiSet.class));
                break;
            case R.id.add_overstep_police:
                //越界报警
                Toast.makeText(mContext, "越界报警", Toast.LENGTH_SHORT).show();
                break;
            case R.id.add_low_power:
                //低电报警
                Toast.makeText(mContext, "低电报警", Toast.LENGTH_SHORT).show();
                break;
            case R.id.add_home_wifi:
                //家庭WIFI
                intentMsg = new Intent(mContext, WifiActivity.class);
                intentMsg.putExtra("imei", ChatActivity.mEntityImei);
                startActivity(intentMsg);
                break;
            case R.id.add_remote_shutdown:
                //远程关机
                sendCommand(MyConstants.REMOTE_CLOSE, R.string.setup_remote_close, R.drawable.power_layout_iv);
                break;
            case R.id.add_remote_listener:
                //远程监听
                intentMsg = new Intent(mContext, RemoteListenerActivity.class);
                intentMsg.putExtra("IMEI", ChatActivity.mEntityImei);
                startActivity(intentMsg);
                /*if ((System.currentTimeMillis() - countTime.get("remote_listener")) > Constants.REQUEST_INTERVAL) {
                    sendCommand(MyConstants.REMOTE_LISTENER, R.string.setup_remote_listener, R.drawable.power_layout_iv);
                    countTime.put("remote_listener", System.currentTimeMillis());
                } else {
                    Toast.makeText(mContext, R.string.foot_menu_prompt, Toast.LENGTH_SHORT).show();
                }*/
                break;
            case R.id.add_alarm:
                //家庭闹钟
                startActivity(new Intent(mContext, AlarmActivity.class));
                break;
            case R.id.step_counting:
                Intent intent = new Intent(mContext, StepCountingActivity.class);
                intent.putExtra("IMEI", ChatActivity.mEntityImei);
                startActivity(intent);
                break;
            case R.id.add_blacklist:
                doBlacklist();
                break;
            default:
                break;
        }
    }

    private void doBlacklist() {
        SharedPreferences sp = Utils.getPreferences(getActivity());
        String key = Constants.PREFIX_BLACKLIST + ChatActivity.mEntityImei;
        boolean isOpen = sp.getBoolean(key, true);
        String cont = getString(R.string.blacklist_opt, isOpen ? getString(R.string.close_lower) : getString(R.string.open_lower));
        sendCommand(CmdType.CS.getType(), cont + " " + getString(R.string.send_success), isOpen ? "0" : "1");
        sp.edit().putBoolean(key, !isOpen).apply();
    }

    private void sendCommand(String type, String cont, String cd) {
        String imei = ChatActivity.mEntityImei;
        ChatMsg chatMsg = createSysChatMsg(imei);
        chatMsg.setContent(cont);

        AppContext.getEventBus().post(chatMsg, Constants.EVENT_TAG_CHAT_DISPLAYMSG);
        saveChatMsg(chatMsg);

        ChatMsg cmdMsg = chatMsg.clone();
        Cmd cmd = new Cmd(type, cd, imei);
        cmdMsg.setContent(cmd.toJson());
        AppContext.getEventBus().post(cmdMsg, Constants.EVENT_TAG_CHAT_SEND);
    }

    private void sendCommand(String type, final int optionContent, final int icon) {
        Cmd cmd;
        String imei = Session.getInstance().getSetupDevice().getImei();
        String phone = Session.getInstance().getUser().getPhone();
        switch (type) {
            case MyConstants.REMOTE_CLOSE:
                cmd = new Cmd(CmdType.OF.getType(), "1", imei);
                break;
            case MyConstants.ELEC_SAVE_SWITCH:
                cmd = new Cmd(CmdType.PO.getType(), "0", imei);
                break;
            case MyConstants.TERM_FEE:
                cmd = new Cmd(CmdType.HF.getType(), null, imei);
                break;
            case MyConstants.REMOTE_LISTENER:
                cmd = new Cmd(CmdType.RC.getType(), "1," + phone, imei);
                break;
            default:
                return;
        }
        ChatMsg chatMsg = createSysChatMsg(ChatActivity.mEntityImei);
        chatMsg.setContent(getString(optionContent) + " " + getString(R.string.send_success));

        AppContext.getEventBus().post(chatMsg, Constants.EVENT_TAG_CHAT_DISPLAYMSG);
        saveChatMsg(chatMsg);

        ChatMsg cmdMsg = chatMsg.clone();
        cmdMsg.setContent(cmd.toJson());
        AppContext.getEventBus().post(cmdMsg, Constants.EVENT_TAG_CHAT_SEND);
    }

    /**
     * 保存聊天信息到数据库
     */
    public void saveChatMsg(ChatMsg chatMsg) {
        try {
            AppContext.db.saveBindingId(chatMsg);
        } catch (Exception e) {
            Log.e(Constants.TAG, "保存聊天信息到数据库失败！", e);
        }
    }

    private ChatMsg createSysChatMsg(String imei) {
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setIsSend(false);
        chatMsg.setImei(imei);
        chatMsg.setType(ContType.CMD.getType());
        chatMsg.setTermType(Session.getInstance().getMapEntityByImei(imei).getTermType().getType());
        chatMsg.setUserId(Session.getInstance().getLoginedUserId());
        chatMsg.setTime(System.currentTimeMillis());
//        chatMsg.setSucc(1);
        return chatMsg;
    }
}
